/* 页面基类 */
import Vue from 'vue'
import './filters'
import './api'
import './request'
import moment from 'moment'
import './fastclick'
import 'vant/lib/index.css'
import '@/assets/style/index.scss'
import defaultPics from './pic-base64'
import InfiniteLoading from 'vue-infinite-loading'
import {
  ImagePreview
} from 'vant';

import './vant.js'



Vue.use(InfiniteLoading)

Vue.prototype.$moment = moment

Vue.prototype.$defaultPics = defaultPics

Vue.config.productionTip = false

// 封装 promise 检查是否获取系统权限 例如 checkSystemAccess('camera', '相机')
Vue.prototype.$checkSystemAccess = function (accessValue, accessName) {
  return new Promise((resolve, reject) => {
    const resultList = api.hasPermission({
      list: [accessValue]
    })
    const granted = resultList[0].granted
    if (granted) {
      // 已授权，可以继续下一步操作
      resolve(true)
    } else {
      api.confirm({
          msg: `应用需要您的授权才能访问${accessName}`,
          buttons: ['取消', '去设置']
        },
        function (ret) {
          // 点击去设置
          if (ret.buttonIndex == 2) {
            api.requestPermission({
                list: [accessValue]
              },
              function (res) {
                if (res.list[0].granted) {
                  resolve(true)
                } else {
                  resolve(false)
                }
              }
            )
          }
        }
      )
    }
  })
}

Vue.prototype.$viewImg = function (imgs = [], index = 1) {
  if (imgs.length) {
    ImagePreview({
      images: imgs,
      startPosition: index,
    });
  }
}

Vue.prototype.$getPic = function (type) {
  return new Promise((resolve, reject) => {
    api.getPicture({
        sourceType: type,
        encodingType: 'jpg',
        mediaValue: 'pic',
        destinationType: 'url',
        allowEdit: false,
        quality: 70,
        targetWidth: 1920,
        targetHeight: 1080,
      },
      (ret, err) => {
        if (err) {
          api.toast({
            msg: '获取图片失败',
            duration: 2000,
            location: 'bottom',
          })
        } else {
          if (ret.data) {
            resolve(ret.data)
          } else {
            api.toast({
              msg: '未选择图片',
              duration: 2000,
              location: 'bottom',
            })
          }
        }
      }
    )
  })
}

Vue.prototype.$fileUpload = async function (files) {
  try {
    let result = await this.$http.upload(
      '/api/Files/UploadFiles?isPublic=true', {
        files
      },
      true
    )
    return result
  } catch (ex) {
    return null
  }
}

Vue.prototype.$scanCode = function () {
  return new Promise((resolve, reject) => {
    this.$checkSystemAccess('camera', '相机').then(_res => {
      if (_res) {
        const FNScanner = api.require('FNScanner');
        FNScanner.open({
          autorotation: false,
        }, function (ret, err) {
          if (ret) {
            if (ret.eventType == 'success' && ret.content != '') {
              // 扫码成功执行函数操作传值
              api.confirm({
                title: '扫描结果',
                msg: ret.content,
                buttons: ['确定', '取消']
              }, (_ret, _err) => {
                let index = _ret.buttonIndex;
                if (index == 1) {
                  resolve(ret.content);
                } else {
                  resolve(false);
                }
              });
              // resolve(ret.content);
            }
            if (ret.eventType == 'cameraError') {
              api.toast({
                msg: '请开启app访问手机摄像头权限',
                duration: 2000,
                location: 'bottom'
              });
              setTimeout(function () {
                // 关闭扫码模块
                FNScanner.closeView();
                reject(false)
              }, 300);
            }
            if (ret.eventType == 'albumError') {
              api.toast({
                msg: '请开启app访问手机相册权限',
                duration: 2000,
                location: 'bottom'
              });
              setTimeout(function () {
                // 关闭扫码模块
                FNScanner.closeView();
                reject(false)
              }, 300);
            }
            if (ret.eventType == 'fail') {
              api.toast({
                msg: '扫码失败,请从新扫码',
                duration: 2000,
                location: 'bottom'
              });
              setTimeout(function () {
                // 关闭扫码模块
                FNScanner.closeView();
                reject(false)
              }, 300);
            }
          } else {
            api.toast({
              msg: '扫码错误请稍后再试',
              duration: 2000,
              location: 'bottom'
            });
            setTimeout(function () {
              // 关闭扫码模块
              FNScanner.closeView();
              reject(false)
            }, 300);
          }
        });
      } else {
        resolve(false);
      }
    })
  })
}
Vue.prototype.$clone = function (obj) {
  let copy

  // Handle the 3 simple types, and null or undefined
  if (obj == null || typeof obj !== 'object') return obj

  // Handle Date
  if (obj instanceof Date) {
    copy = new Date()
    copy.setTime(obj.getTime())
    return copy
  }

  // Handle Array
  if (obj instanceof Array) {
    copy = []
    for (let i = 0, len = obj.length; i < len; i++) {
      copy[i] = clone(obj[i])
    }
    return copy
  }

  // Handle Object
  if (obj instanceof Object) {
    copy = {}
    for (const attr in obj) {
      if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr])
    }
    return copy
  }

  throw new Error("Unable to copy obj! Its type isn't supported.")
}
export default function (options, cb) {
  // new Vue(options);
  // console.log(window.navigator.platform)

  function vuePage() {
    var vue = new Vue(options)
    // 需要时返回构建好的vue对象,通过回调方式;
    if (typeof cb === 'function') {
      cb(vue)
    }
  }

  if (window.navigator.platform == 'Win32') {
    vuePage()
  }
  window.apiready = function () {
    // pages.appWidth = api.winWidth
    // pages.appHeight = api.winHeight
    // ios click event 300ms
    if (api.systemType === 'ios') {
      FastClick.attach(document.body)
    }
    var vue = new Vue(options)
    // 需要时返回构建好的vue对象,通过回调方式;
    if (typeof cb === 'function') {
      cb(vue)
    }
  }
}